<script setup lang="tsx">
import { nextTick, onMounted, ref } from "vue";
import { TableInstance } from "element-plus";

const tableData = ref([
  {
    id: 1,
    name: "Alice",
    age: 25,
    type: "No. 189, Grove St, Los Angeles",
    updateTime: "192093102930122222222222222222",
    system: "12333333333333333333333333",
    status: "120",
  },
  { id: 2, name: "Bob", age: 30, type: "No. 189, Grove St, Los Angeles" },
  { id: 3, name: "Charlie", age: 22 },
  { id: 3, name: "Dill", age: 22 },
]);
const isEdit = ref(false);
const index = ref(0);
const handleEdit = (scope: { $index: number }) => {
  if (!isEdit.value) {
    index.value = scope.$index;
    isEdit.value = true;
  } else {
    isEdit.value = false;
  }
};

const handleDelete = (scope: { $index: number }) => {
  tableData.value.splice(scope.$index, 1);
};

const handleAdd = () => {
  tableData.value.unshift({
    id: 1,
    name: "",
    age: null,
    type: "",
    updateTime: "",
    system: "",
    status: "",
  });
  isEdit.value = true;
  index.value = 0;
};
const column = [
  {
    label: "名称",
    prop: "name",
    width: 200,
  },
  {
    label: "类型",
    prop: "type",
  },
  {
    label: "更新时间",
  },
  {
    label: "系统内置",
    prop: "system",
    showOverflowTooltip: true,
  },
  {
    label: "状态",
    prop: "status",
  },
  {
    label: "操作",
    render: (scope: { $index: number }) => {
      return (
        <>
          <el-button
            type="primary"
            size="small"
            onClick={() => handleEdit(scope)}
          >
            {isEdit.value && scope.$index === index.value ? "确定" : "编辑"}
          </el-button>
          <el-button
            type="danger"
            size="small"
            onClick={() => handleDelete(scope)}
          >
            删除
          </el-button>
        </>
      );
    },
  },
].map((item) => {
  return {
    ...item,
    render: item.render
      ? item.render
      : (scope: any) => {
          return isEdit.value && scope.$index === index.value ? (
            <el-input
              v-model={scope.row[item.prop as keyof typeof scope.row]}
            />
          ) : (
            scope.row[item.prop as keyof typeof scope.row]
          );
        },
  };
});
const refTable = ref<TableInstance>();

const page = ref(2);

onMounted(async () => {
  await nextTick();
});
</script>

<template>
  <el-card header="可操作编辑删除的表格">
    <el-button type="primary" style="margin-bottom: 12px" @click="handleAdd">
      添加一行
    </el-button>
    <nf-table
      ref="refTable"
      :data="tableData"
      :column="column"
      :max-height="300"
      stripe
      border
      pagination
      :pagination-config="{
        total: 100,
        defaultCurrentPage: page,
        layout: 'prev,pager,next, ->, total',
        background: true,
        onCurrentChange: (_page) => {
          console.log(_page);
        },
      }"
    >
    </nf-table>
  </el-card>
</template>

<style scoped lang="scss"></style>
